//
//  ViewHelp.swift
//  DanTangLKM
//
//  Created by LKM on 16/8/19.
//  Copyright © 2016年 LKM. All rights reserved.
//

import UIKit
import Foundation
import SVProgressHUD
import Toast_Swift

open class ViewHelp {

    /*
    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func drawRect(rect: CGRect) {
        // Drawing code
    }
    */
    
    class func getScreenWidth()->CGFloat{
        return UIScreen.main.bounds.size.width;
    }
    
    /**
     高度更宽度会不加
    */
    class func GONE(_ view:UIView){
        view.isHidden=true;
    }
    
    class func removeAllSubView(_ v:UIView?){
        v?.subviews.forEach({ $0.removeFromSuperview() }) // this gets things done
//        v.subviews.map({ $0.removeFromSuperview() }) // this returns modified array
    }
    
    class func getViewForXib(_ xib:String) ->UIView?{
        return Bundle.main.loadNibNamed(xib, owner: nil, options: nil)!.last as! UIView? ;
    }
    /**
     内容是否为空
     */
    class func isTextEmpty(_ tx: UITextField)->Bool{
        return ( tx.text == nil || (tx.text?.isEmpty  )! );
    }
    
    class func setTextColor(_ v:UIButton, _ c:UIColor){
        v.setTitleColor(c, for: UIControlState())//UIControlState.normal)
    }
    
    /**
     点击事件 监听
     onProductFilterItemClick(_ rg:UITapGestureRecognizer )
     Selector 其实是不能在外面确定参数的。也就是代码已经固定上面那个函数签名了
     */
    public class func setOnClickListening(_ view:UIView ,_ target :Any,_ action: Selector?){
        view.isUserInteractionEnabled=true;
        view.addGestureRecognizer(UITapGestureRecognizer(target: target, action: action ) )

    }
    public class func setOnClickListening(_ view:UIControl ,_ target :Any,_ action: Selector){
//        view.isUserInteractionEnabled=true;
//        view.addGestureRecognizer(UITapGestureRecognizer(target: target, action: action ) )
        view.addTarget(target, action: action, for:UIControlEvents.touchUpInside)
    }

    public class func setPadding(_ view:UIButton, pa:CGFloat){
        ViewHelp.setPadding(view,pa,pa,pa,pa)
    }
    public class func setPadding(_ view:UIButton ,_ top: CGFloat, _ left: CGFloat, _ bottom: CGFloat, _ right: CGFloat){
        view.contentEdgeInsets = UIEdgeInsetsMake(top, left, bottom, right)
//        var v:UIView;
//        v.layoutMargins
    }
    
    
    public class func setHtmlText(_ view:UILabel,_ str:String){
        do{
            let attrStr = try NSAttributedString(data: str.data(using: String.Encoding.unicode, allowLossyConversion: true)!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
            view.attributedText = attrStr
        }catch let error as NSError {
            print(error.localizedDescription)
        }
    }
    
    public class func findViewWithTag(view:UIView ,tag:Int)->UIView?{
        return view.viewWithTag(tag);
    }

    /**
     
     调用多少次 就得调用多少次hideProgressActivity();
     */
    public class func showProgressActivity(containView:UIView,tips:String?=""){
    
        containView.showProgressActivity(tips: tips);
    }
    
    public class func showProgressActivityDelay(containView:UIView,tips:String?="") {
        //先这样
        showProgressActivity(containView:containView,tips:tips)
    }
    
    public class func hideProgressActivity(containView:UIView){
        containView.hideProgressActivity()
    }

  
    public class func showAlertTipsDialog(tips:String,okBtn:String="确定", okRun : (()->())?) {
        let cc  = { () -> UIAlertViewDelegate? in
            
            // 得继承NSObject 才能ok，不然会报：does not conform to protocol 'NSObjectProtocol'
            // 继承是为了适配oc？
            class MUIAlertViewDelegate : NSObject, UIAlertViewDelegate{
                let run:(()->Void)? ;
                //因为class就相当于java中的static class 所以得传值
                init(run:(()->())? ) {
                    self.run=run;
                    super.init()
                }

                fileprivate func alertView(_ alertView: UIAlertView, didDismissWithButtonIndex buttonIndex: Int) {
                    run?();
                }
                
            }
            return MUIAlertViewDelegate(run: okRun);
        }()
        
        let av = UIAlertView(title: nil, message: tips, delegate: cc, cancelButtonTitle: okBtn);//
        av.setTag( "MUIAlertViewDelegate_cycle", cc);//得把这个对象弄个强引用才行
        av.show();
        
        
    }
    public class func showAlertDialog(title:String = "",tips:String,okBtn:String="确定",cancleBtn:String="取消", okRun : (()->())?, cancleRun : (()->())?){
        let cc = { () -> UIAlertViewDelegate? in
            class MUIAlertViewDelegate : NSObject, UIAlertViewDelegate{
                let okRun:(()->Void)? ;
                let cancleRun :(()->Void)? ;
                
                //因为class就相当于java中的static class 所以得传值
                init(okRun:(()->())? ,cancleRun :(()->())?) {
                    self.okRun=okRun;
                    self.cancleRun=cancleRun;
                    super.init()
                }
                fileprivate func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int) {
                    if(buttonIndex==1){
                        okRun?();
                    }else if(buttonIndex==0){//取消
                        cancleRun?();
                    }
                }
                
                
            }
            return MUIAlertViewDelegate(okRun: okRun,cancleRun:cancleRun);
        }()

        let av = UIAlertView(title: title, message: tips, delegate: cc, cancelButtonTitle: cancleBtn,otherButtonTitles: okBtn);//
        av.setTag("MUIAlertViewDelegate_cycle", cc);//得把这个对象弄个强引用才行
        av.show();

    }
    
    public class func showDialogView(_ viewController: UIViewController ,view :UIView){
        let av = UIAlertController(title: "", message: nil, preferredStyle: UIAlertControllerStyle.actionSheet)
        
//        var ok:UIAlertAction=UIAlertAction(title: "ok", style: UIAlertActionStyle.default, handler: nil)
//        av.addAction(ok)
        
        ViewHelp.removeAllSubView(av.view);
        
        av.view.addSubview(view)
        // show the alert
        viewController.present(av, animated: true, completion: nil)
    }

    
    public class func showSingleList(_ viewController: UIViewController ,title:String = "",tips:String,mItems:[String] ,selectItem:String?,onItemClick:@escaping (_ index:Int)->() ,cancleRun : (()->())? ){
        let av = UIAlertController(title: title, message: tips, preferredStyle: UIAlertControllerStyle.actionSheet)
        
        let handel={
            (mUIAlertAction : UIAlertAction)->() in
            
            if let clickIndex = mUIAlertAction.getTag(&R.id.tag) as? Int {
            
                onItemClick(clickIndex);
            }else{
                cancleRun?();
            }
            
            //Todo
        }
        
        av.addAction(UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel, handler: handel))
        
        var index=0;
        for s in mItems{
            let a=UIAlertAction(title: s, style: s==selectItem! ? UIAlertActionStyle.destructive :UIAlertActionStyle.default, handler: handel)
            a.setTag(&R.id.tag, index);
            av.addAction(a)
            index += 1;
        }
        
        // show the alert
        viewController.present(av, animated: true, completion: nil)
    }
    

    
    public class func showTipsView(containView:UIView,tips:String?){
        if StringHelp.isEmpty(tips){
            return;
        }
            containView.makeToast(tips!,duration: 2.0, position: .center)
        
    }
    public class func showTipsView(containView:UIView,tips:String?,duration:TimeInterval){
        if StringHelp.isEmpty(tips){
            return;
        }
        containView.makeToast(tips!,duration: duration, position: .center)
        
    }
    public class func showTipsViewLong(containView:UIView,tips:String){
        if StringHelp.isEmpty(tips){
            return;
        }
        
        containView.makeToast(tips,duration: 3.0, position: .center)
    }
//    public class func showTipsView(containView:UIView,customView: UIView, duration: TimeInterval, position: ToastPosition, completion: ((_ didTap: Bool) -> Void)?){
//        
//        containView.showToast(customView, duration: duration, position: position, completion:position)
//    }
    
    
    public class func setViewWidthHeigth(_ view:UIView,_ w:CGFloat,_ h:CGFloat){
    
        var tempFrame: CGRect = view.frame
        tempFrame.size.width = w
        tempFrame.size.height = h
        view.frame = tempFrame
        
    }
    public class func setViewHeigth(_ view:UIView,_ h:CGFloat){
        var tempFrame: CGRect = view.frame
        tempFrame.size.height = h
        view.frame = tempFrame

    }
    public class func setViewWidth(_ view:UIView,_ w:CGFloat){
        var tempFrame: CGRect = view.frame
        tempFrame.size.width = w
        view.frame = tempFrame
    }
    
    

}
